package com.gz.mylife.app;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.adapter.BaseAdapterHelper;
import com.gz.mylife.adapter.QuickAdapter;
import com.gz.mylife.widget.FooterView;
import com.gz.mylife.widget.LoadingCover;
import com.gz.mylife.widget.OfflineDialog;
import com.gz.mylife.widget.FooterView.OnFooterViewRefreshListener;
import com.gz.mylife.widget.LoadingCover.OnLoadingCoverRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.zl.smartmall.library.ISmartMall;
import com.zl.smartmall.library.listener.ProductEvaluationDetailListener;
import com.zl.smartmall.library.listener.RequestCode;
import com.zl.smartmall.library.po.ProductEvaluationInfo;
import com.zl.smartmall.library.util.Tools;

public class ProductCommentDetail extends BaseActivity implements OnRefreshListener<ListView>, OnClickListener, OnFooterViewRefreshListener, OnLoadingCoverRefreshListener {

	private static final String TAG = ProductCommentDetail.class.getSimpleName();
	private int mPage;
	private DisplayImageOptions mImageOptions;
	private LayoutInflater mInflater;
	private QuickAdapter<ProductEvaluationInfo> mAdapter;

	private FooterView mFooterView;
	private LoadingCover mLoadingCover;
	private OfflineDialog mOfflineDialog;
	private PullToRefreshListView mPullList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_product_comment_detail);
		
		mInflater = getLayoutInflater();
		initAdapter();
		initImageOptions();

//		mActionBar.setTitle("评价详情");
		setActionbarTitle("评价详情", true);
		mFooterView = (FooterView) mInflater.inflate(R.layout.footer_view, null);
		mFooterView.setOnFooterViewRefreshListener(this);
		
		mLoadingCover = (LoadingCover) findViewById(R.id.layout_loading_cover);
		mLoadingCover.setOnLoadingCoverRefreshListener(this);

		mOfflineDialog = (OfflineDialog) mInflater.inflate(R.layout.offline_dialog, null);
		
		mPullList = (PullToRefreshListView) findViewById(R.id.list);
		mPullList.getRefreshableView().addFooterView(mFooterView);
		mPullList.setOnRefreshListener(this);
		mPullList.setOnScrollListener(mFooterView);
		mPullList.setAdapter(mAdapter);
		
		loadDataFromServer(buildListener(RequestCode.PULL));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.product_comment_detail, menu);

//		MenuItemCompat.setShowAsAction(menu.findItem(R.id.action_comment),
//				MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
		menu.findItem(R.id.action_comment).setVisible(false);

//		MenuItemCompat.setShowAsAction(menu.findItem(R.id.action_quick_navigate),
//				MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.action_comment:
//			Intent intent = new Intent(getApplicationContext(), ProductCommentIssue.class);
//			intent.putExtra("productId", getIntent().getIntExtra("productId", 0));
//			startActivity(intent);
			return true;
		
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
//		PictureInfo info = (PictureInfo) v.getTag();
//		Intent photoPreview = new Intent(this, HDImagePreview.class);
//		photoPreview.putExtra("images", info.url.toArray());
//		photoPreview.putExtra("position", info.position);
//		startActivity(photoPreview);
	}

//	@Override
//	public void onCoverClick() {
//		// TODO Auto-generated method stub
//		loadDataFromServer();
//	}
//
//	@Override
//	public void onFooterViewClick() {
//		// TODO Auto-generated method stub
//		mLastId = mAdapter.getItem(mAdapter.getCount() - 1).getCommentId();
//		loadDataFromServer();
//	}

	@Override
	public void onFooterViewRefresh() {
		// TODO Auto-generated method stub
		loadDataFromServer(buildListener(RequestCode.SCROLL));
	}

	@Override
	public void onLoadingCoverRefresh() {
		// TODO Auto-generated method stub
		loadDataFromServer(buildListener(RequestCode.PULL));
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		loadDataFromServer(buildListener(RequestCode.PULL));
	}
	
	private ProductEvaluationDetailListener buildListener(RequestCode requestCode) {
		return new ProductEvaluationDetailListener(requestCode) {
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				if(mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshFailed();
				}
				mLoadingCover.onRefreshFailed();
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
				if(mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshFailed();
				}
				mLoadingCover.onRefreshFailed(Define.MSG_OFFLINE_ERROR);
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				if(mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshFailed();
				}
				mLoadingCover.onRefreshFailed(Define.MSG_NO_NETWORK);
			}
			
			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed(Define.MSG_NOTHING);
				mFooterView.onRefreshComplete();
				mPullList.setOnScrollListener(null);
				if(mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshSuccess();
				}
			}
			
			@Override
			public void onResponseSuccess(List<ProductEvaluationInfo> productEvaluationInfos) {
				// TODO Auto-generated method stub
				if(this.requestCode == RequestCode.PULL) {
					mAdapter.clear();
				}
				mAdapter.addAll(productEvaluationInfos);
				mLoadingCover.onRefreshSuccess();
				if(mPullList.isRefreshing()) {
					mPullList.getLoadingLayoutProxy().refreshSuccess();
				}
				if(productEvaluationInfos.size() < Define.LISTVIEW_ITEM_MIN_SIZE){
					mFooterView.onRefreshComplete();
					mPullList.setOnScrollListener(null);
				}else {
					mFooterView.onRefreshSuccess();
					mPullList.setOnScrollListener(mFooterView);
				}
			}
		};
	}
	
	private void initImageOptions(){
		mImageOptions = new DisplayImageOptions.Builder()
        .resetViewBeforeLoading(true)
        .bitmapConfig(Bitmap.Config.ARGB_8888)
        .cacheInMemory(true)
        .cacheOnDisk(true)
        .showImageOnLoading(R.drawable.ic_load_image_square_default)
        .showImageOnFail(R.drawable.ic_load_image_square_fail)
        .showImageForEmptyUri(R.drawable.ic_load_image_square_fail)
        .imageScaleType(ImageScaleType.EXACTLY)
        .build();
	}
	
	private void initAdapter() {
		List<ProductEvaluationInfo> list = new ArrayList<ProductEvaluationInfo>();
//		for(int i = 0; i < 10; i++) {
//			list.add(null);
//		}
		mAdapter = new QuickAdapter<ProductEvaluationInfo>(getApplicationContext(), R.layout.product_comments_item, list) {
			
			@Override
			protected void convert(BaseAdapterHelper helper, ProductEvaluationInfo item) {
				// TODO Auto-generated method stub
				if(item != null) {
					ImageView[] picture = new ImageView[]{
							helper.getView(R.id.iv_picture1),
							helper.getView(R.id.iv_picture2),
							helper.getView(R.id.iv_picture3),
							helper.getView(R.id.iv_picture4)
					};
					
					PictureInfo info = new PictureInfo();
					for(com.zl.smartmall.library.po.PictureInfo pictureModel : item.getPictures()) {
						info.url.add(pictureModel.getUrl());
					}
					
					for(int i = 0; i < 4; i++) {
						if(i < item.getPictures().size()) {
							info.position = i;
							picture[i].setTag(info);
							picture[i].setVisibility(View.VISIBLE);
							ImageLoader.getInstance().displayImage(
									item.getPictures().get(i).getUrl(), 
									picture[i], mImageOptions);
						}else {
							picture[i].setVisibility(View.GONE);
						}
						picture[i].setOnClickListener(ProductCommentDetail.this);
					}
					helper.setImageUrl(R.id.iv_portrait, item.getFace(), mImageOptions)
						  .setText(R.id.tv_nickname, item.getNickname())
						  .setText(R.id.tv_content, item.getCommentContent())
						  .setText(R.id.tv_date, Tools.formatTimeStampString(getApplicationContext(), item.getCommentTime(), false));
				}
			}
		};
	}

	private void loadDataFromServer(ProductEvaluationDetailListener productEvaluationDetailListener) {
		if(productEvaluationDetailListener.getRequestCode() == RequestCode.PULL) {
			mPage = 0;
			
		}else if(productEvaluationDetailListener.getRequestCode() == RequestCode.SCROLL) {
			mPage = mAdapter.getItem(mAdapter.getCount() - 1).getCommentId();
		}
		ISmartMall.getInstance().getProductEvaluationDetail(getIntent().getIntExtra("productId", 0), mPage, productEvaluationDetailListener);
	}

	private static class PictureInfo {
		List<String> url = new ArrayList<String>();
		int position;
	}
}
